/**
 * @author 伟健 / 张
 * @return 文件说明：  该文件用于node后台和客户端通信。 接受事件，发送事件
 */
const { ipcMain, dialog, shell, BrowserWindow, globalShortcut } = require("electron");
const path = require("path");
const fs = require("fs");
const Store = require("electron-store");
const store = new Store();
let config = store.get("config");
const mkdirp = require("mkdirp");
var xlsx = require("node-xlsx");
let filePathArr = [];

ipcMain.handle("addFile", async (event, data) => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    filters: [
      {
        name: "选择文件",
        extensions: ["xlsx"],
      },
    ],
    properties: ["openFile", "multiSelections"],
  });
  if (canceled) {
    filePathArr = [];
    return null;
  } else {
    filePathArr = filePaths;
    return filePaths;
  }
});
ipcMain.handle("transform", async (event, data) => {
  if (filePathArr.length) {
    const options = {
      "!cols": [{ wch: 30 }, { wch: 35 }, { wch: 35 }, { wch: 35 }, { wch: 35 }, { wch: 35 }, { wch: 35 }, { wch: 135 }],
    };
    filePathArr.forEach((_path) => {
      var obj = xlsx.parse(_path);
      // console.log(obj);
      exec(obj[1]["data"]);
      function exec(data) {
        const xlsx_data = [["项目名称", "车牌号", "运输记录（商品名称）", "商品编号", "商品名称", "单位", "数量", "运输起始地", "运输目的地（垃圾，土，水泥块，砖渣）"]];

        data.forEach((item, index) => {
          if (index && item.length == 7) {
            // 0，2，7，8

            let vehicle = item[1].split("/");
            let origin = item[5].split("/");
            let destination = item[6].split("/");
            let name = item[0];
            vehicle.forEach((el, index) => {
              xlsx_data.push([name, "", el, "", "", "", "", origin[index], destination[index]]);
            });
          }
        });

        const buffer = xlsx.build([{ name: "转换文件", data: xlsx_data }], options); // 拿到文件 buffer
        let filename = path.basename(_path);

        // 写入文件

        fs.writeFileSync(path.resolve(_path, "../", `${filename}-转换文件.xlsx`), Buffer.from(buffer));
        // fs.writeFileSync(`${__dirname}/导出文件.xlsx`, Buffer.from(buffer));
      }
      // 生成 buffer
    });
  }
});
//

module.exports = async function (_win) {
  win = _win;
};
